
# myapp/models.py

from django.db import models
from django.utils import timezone
from django.urls import reverse
from taggit.managers import TaggableManager

class User(models.Model):
    username = models.CharField(max_length=100, unique=True)
    password = models.CharField(max_length=128)
    email = models.EmailField()

    class Meta:
        db_table = "user"


class UserProfile(models.Model):
    GENDER_CHOICES = (
        ('M', '男'),
        ('F', '女'),
        ('O', '其他'),
    )

    user = models.OneToOneField(User, on_delete=models.CASCADE)
    mobile = models.CharField('手机号码', max_length=11)
    gender = models.CharField('性别', max_length=1, choices=GENDER_CHOICES)
    id_card = models.CharField('身份证号', max_length=18)
    student_id = models.CharField('学号', max_length=20)
    age = models.IntegerField('年龄', default=18)

    class Meta:
        verbose_name = '用户档案'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.user.username

# orders/models.py
class Product(models.Model):
    """商品模型"""
    name = models.CharField(max_length=255)
    description = models.TextField()
    price = models.DecimalField(max_digits=10, decimal_places=2)
    image = models.ImageField(upload_to='products/')  # 商品图片
    stock = models.PositiveIntegerField()

    def __str__(self):
        return self.name

class Order(models.Model):
    """订单模型"""
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    order_number = models.CharField(max_length=20, unique=True)
    created_at = models.DateTimeField(default=timezone.now)
    total_price = models.DecimalField(max_digits=10, decimal_places=2)
    status = models.CharField(
        max_length=20,
        choices=[
            ('pending', '待支付'),
            ('paid', '已支付'),
            ('shipped', '已发货'),
            ('completed', '已完成')
        ],
        default='pending'
    )


    def __str__(self):
        return self.order_number

class OrderItem(models.Model):
    """订单项模型"""
    order = models.ForeignKey(Order, on_delete=models.CASCADE)
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    quantity = models.PositiveIntegerField()
    unit_price = models.DecimalField(max_digits=10, decimal_places=2)

    def __str__(self):
        return f"{self.product.name} x{self.quantity}"

class Product_order(models.Model):
    CONDITION_CHOICES = [
        ('NEW', '全新未使用'),
        ('LIKE_NEW', '几乎全新'),
        ('GOOD', '使用痕迹少'),
        ('FAIR', '有明显使用痕迹'),
    ]
    CATEGORY_CHOICES = [
        ('ELECTRONICS', '数码电子'),
        ('CLOTHING', '服饰鞋包'),
        ('HOME', '家居生活'),
        ('BOOKS', '图书文具'),
        ('OTHERS', '其他'),
    ]

    # 修复字段定义
    category = models.CharField(
        max_length=20,
        choices=CATEGORY_CHOICES,
        default='ELECTRONICS',
        verbose_name="分类"
    )
    name = models.CharField(max_length=100, verbose_name="商品名称")
    description = models.TextField(verbose_name="商品描述")
    price = models.DecimalField(max_digits=10, decimal_places=2, verbose_name="价格")
    created_at = models.DateTimeField(auto_now_add=True,null=True)
    tags = TaggableManager(blank=True)
    condition = models.CharField(
        max_length=20,
        choices=CONDITION_CHOICES,
        default='USED',
        verbose_name="成色"
    )
    image = models.ImageField(upload_to='products/', verbose_name="商品图片")
    location = models.CharField(
        max_length=100,
        verbose_name="所在地",
        default='未知地区'  # 新增默认值
    )

    seller_name = models.CharField(
        max_length=50,
        verbose_name="卖家名称",
        default='匿名卖家'  # 新增默认值
    )
    contact = models.CharField(
        max_length=50,
        verbose_name="联系方式",
        default='暂无联系方式'  # 保留唯一正确的定义
    )
    is_sold = models.BooleanField(default=False, verbose_name="是否售出")
    views = models.IntegerField(default=0, verbose_name="浏览数")
    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse('product_detail', args=[str(self.id)])


class ChatHistory(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    timestamp = models.DateTimeField(auto_now_add=True)
    message = models.TextField()
    response = models.TextField()
    image = models.ImageField(upload_to='chat_images/', null=True)

    class Meta:
        ordering = ['-timestamp']

